<template>
  <el-container style="height: 90vh">
    <el-aside width="35vw">
      <el-row style="padding-top: 5px; padding-bottom: 5px">
        <el-card style="width: 100%;">
          <span>平台：</span>
          <el-select v-model="platform" style="width: 7vw;">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <span style="margin-left: 10px">日期：</span>
          <el-date-picker
              v-model="date"
              type="date"
              placeholder="日期"
              :size="'default'"
              style="width: 7vw;"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disableFutureDates"
          />
          <el-button @click="selectHotpoint" style="width: 5vw; margin-left: 10px" type="primary">查询</el-button>
        </el-card>
      </el-row>
      <el-row style="height: 90%">
        <el-table
            :data="tableData"
            style="width: 100%"
            height="100%"
            border
            @row-click="handleSelect"
        >
          <el-table-column type="index" label="编号" width="53" align="center" />
          <el-table-column prop="hotTitle" label="热搜名称" width="180" align="center" show-overflow-tooltip />
          <el-table-column prop="hotRank" label="最高排名" width="81" align="center" show-overflow-tooltip />
          <el-table-column prop="hotTime" label="上榜时间" width="81" align="center" show-overflow-tooltip />
          <el-table-column prop="hotPlatform" label="平台" align="center" show-overflow-tooltip />
        </el-table>
      </el-row>
    </el-aside>

    <el-main>
      <el-row :gutter="20" style="margin-bottom: 10px">
        <el-col :span="24">
          <el-card>
            <el-row>
              <el-col :span="6">
                <el-statistic title="热搜名称" :value="hotTitle" :value-style="{ fontSize: '14px' }" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="舆情情感倾向" :value="mood" :value-style="{ color: moodColor, fontSize: '16px' }" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="在榜时间" :value="duration_minutes" :formatter="(value: number) => `${value} 分钟`" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="最高舆情热度" :value="hotFever" />
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <div class="chart-container">
        <div class="chart-wrapper" id="chart1"></div>
      </div>
      <el-row :gutter="20" style="margin-top: 10px">
        <el-col :span="12">
          <el-card class="dashboard-card">
            <div class="card-header">
              <div class="card-title">当日排名变化</div>
            </div>
            <div id="chart2" style="height: 250px"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="dashboard-card">
            <div class="card-header">
              <div class="card-title">用户精选评论</div>
            </div>
            <el-carousel height="250px">
              <el-carousel-item v-for="item in userCommon" :key="item">
                <div class="comment-container">
                  <div class="comment-content">{{ item }}</div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import moment from "moment/moment";

onMounted(() => {
  initChart()
  initLineChart()
  selectHotpoint()
})

// 禁用未来日期的方法
const disableFutureDates = (time: Date) => {
  return time.getTime() > Date.now();
};

const date = ref(moment().format('YYYY-MM-DD'))
const platform = ref("weibo")

const options = ref([
    {
      value: 'weibo',
      label: '微博'
    },
    {
      value: 'bilibili',
      label: 'B站'
    }
])

// 保存图表实例
const chartRef = ref<echarts.ECharts | null>(null);

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('chart1');
  if (chartDom) {
    chartRef.value = echarts.init(chartDom);
    updateChart(); // 初始化时渲染
  }
}

// 更新图表数据
const updateChart = () => {
  if (!chartRef.value) return;

  const newOption = {
    ...option, // 保留原有配置
    series: [{
      ...option.series[0],
      data: chartData.value // 更新数据
    }]
  };

  chartRef.value.setOption(newOption);
};

// 表格数据
const tableData = ref()

// 查询热搜
const selectHotpoint = () => {
  // console.log(data.value);
  if (date.value === '' || date.value === undefined || date.value === null) {
    ElMessage.warning('请选择日期！')
    return
  }
  axios.get(window.BASE_URL + '/api/hotSearch/getHotDataTime/' + platform.value + '/' + date.value).then(res => {
    // console.log(res);
    if (res.data.flag) {
      tableData.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

// 用户精选评论
const userCommon = ref(['暂无'])

const currentRow = ref()
const mood = ref<Number | string>('--')
const moodColor = ref()
const duration_minutes = ref<Number | string>('--')
const hotFever = ref<Number | string>('--')
const hotTitle = ref<Number | string>('--')

const ifSuccess = ref<Boolean>(false)

// 获得热搜分析数据
const handleSelect = (row: any) => {
  currentRow.value = row
  // console.log(currentRow);
  axios.get(`${window.BASE_URL}/api/hotSearch/getAnalysisByTitle/${currentRow.value.hotPlatform}/${encodeURIComponent(currentRow.value.hotTitle)}`).then(res => {
    // console.log(res);
    if (res.data.flag) {
      ifSuccess.value = true
      duration_minutes.value = Number(currentRow.value.duration_minutes)
      hotFever.value = Number(currentRow.value.hotFever)
      hotTitle.value = currentRow.value.hotTitle
      chartData.value = [
        { value: res.data.data.sentimentAnalysis.Positive, name: '积极' },
        { value: res.data.data.sentimentAnalysis.Negative, name: '消极' },
        { value: res.data.data.sentimentAnalysis.Neutral, name: '中立' }
      ]
      updateChart()
      switch (res.data.data.judge) {
        case 'Positive' :{
          mood.value = '积极'
          moodColor.value = '#67C23A'
          break
        }
        case 'Negative' :{
          mood.value = '消极'
          moodColor.value = '#F56C6C'
          break
        }
        case 'Neutral' :{
          mood.value = '中立'
          moodColor.value = '#909399'
          break
        }
      }
    } else {
      ifSuccess.value = false
      chartData.value = [
        { value: 1, name: '积极' },
        { value: 1, name: '消极' },
        { value: 1, name: '中立' }
      ]
      updateChart()
      duration_minutes.value = '--'
      hotFever.value = '--'
      hotTitle.value = '--'
      mood.value = '--'
      ElMessage.error(res.data.msg)
    }
  });
  axios.get(`${window.BASE_URL}/api/hotSearch/getHotDataAndClassifyByTitleNameAndDate/${currentRow.value.hotPlatform}/${encodeURIComponent(currentRow.value.hotTitle)}/${date.value}`).then(res => {
    // console.log(res);
    if (res.data.flag && ifSuccess.value) {
      xAxisData.value = res.data.data.date;
      yAxisData.value = res.data.data.rank;
      updateLineChart();
    } else {
      ifSuccess.value = false
      xAxisData.value = ['==>', '当', '前', '暂', '无', '数', '据', '<=='];
      yAxisData.value = [10, 8, 5, 3, 3, 5, 8, 10]
      updateLineChart();
    }
  });
  axios.get(`${window.BASE_URL}/api/hotSearch/getHotSearchComment/${currentRow.value.hotPlatform}/${encodeURIComponent(currentRow.value.hotTitle)}`).then(res => {
    // console.log(res);
    if (res.data.flag && ifSuccess.value) {
      userCommon.value = res.data.data
    } else {
      ifSuccess.value = false
      userCommon.value = ['暂无']
    }
  })
}

// 环形图配置
const chartData = ref([
  { value: 1, name: '积极' },
  { value: 1, name: '消极' },
  { value: 1, name: '中立' }
]);

const option = {
  title: {
    text: '用户情感统计',    // 标题文本
    left: 'center',        // 水平居中
    top: '3%',             // 距离顶部距离
    textStyle: {
      color: '#333',       // 字体颜色
      fontSize: 18,        // 字体大小
      fontWeight: 'bold'   // 加粗
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: (params: any) => {
      return `
        <div style="
          margin: 0;
          padding: 8px;
          text-align: left; /* 全局左对齐 */
          font-family: Arial, sans-serif; /* 统一字体 */
        ">
          <!-- 分类名称行 -->
          <div style="
            display: flex;
            align-items: center;
            margin-bottom: 6px;
          ">
            <span style="
              display: inline-block;
              width: 10px;
              height: 10px;
              background: ${params.color};
              border-radius: 50%;
              margin-right: 8px;
              flex-shrink: 0; /* 防止图标挤压 */
            "></span>
            <span style="
              font-weight: 600;
              color: #333;
              white-space: nowrap; /* 防止换行 */
            ">
              ${params.name}
            </span>
          </div>

          <!-- 数据行 -->
          <div style="line-height: 1.6">
            <div style="display: flex; justify-content: space-between">
              <span style="color: #666; margin-right: 15px">数量：</span>
              <span style="color: #409EFF">${params.value}</span>
            </div>
            <div style="display: flex; justify-content: space-between">
              <span style="color: #666; margin-right: 15px">占比：</span>
              <span style="color: #67C23A">${params.percent}%</span>
            </div>
          </div>
        </div>
      `;
    }
  },
  legend: {
    top: '15%',
    // right: '5%',
    left: 'center',
    orient: 'horizontal', // 水平排列
    itemGap: 15          // 图例项间距
  },
  grid: {                // 内容区域留白
    top: '20%',
    bottom: '15%'
  },
  series: [
    {
      name: '情感',
      type: 'pie',
      center: ['50%', '60%'],
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: false,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: chartData.value
    }
  ]
};

// 折线图配置
const xAxisData = ref(['==>', '当', '前', '暂', '无', '数', '据', '<=='])
const yAxisData = ref([10, 8, 5, 3, 3, 5, 8, 10])

const lineChartOption = {
  title: {
    text: '热搜排名变化趋势',
    left: 'center',
    top: '3%',          // 标题距离容器顶部的距离
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold',
      padding: [0, 0, 5, 0] // 标题文本的底部内边距（下方增加 5px 空隙）
    }
  },
  tooltip: {
    trigger: 'item',
    backgroundColor: '#fff',
    borderColor: '#eee',
    textStyle: {
      color: '#333',
      fontSize: 14
    },
    formatter: (params: any) => {
      return `
        <div style="
          margin: 0;
          padding: 6px;  /* 缩小内边距 */
          min-width: 140px;  /* 缩小最小宽度 */
          font-family: Arial, sans-serif;
        ">
          <div style="
            font-size: 13px;  /* 标题字号缩小 */
            font-weight: 600;
            color: #303133;
            margin-bottom: 4px;  /* 缩小间距 */
          ">
            ${params.name}
          </div>
          <div style="line-height: 1.5;">
            <div style="display: flex; justify-content: space-between; margin: 4px 0;">
              <span style="color: #606266;">排名：</span>
              <span style="color: #409EFF; margin-left: 10px;">${params.value}</span>
            </div>
          </div>
        </div>
      `;
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    position: 'bottom', // 明确指定位置
    axisLabel: {
      // 截断文本并添加省略号
      formatter: (value: string) => {
        const maxLength = 6 // 最大显示字符数（根据实际宽度调整）
        return value.length > maxLength
            ? `${value.substring(0, maxLength)}...`
            : value
      },
      rotate: 45,          // 倾斜45度防止重叠
      interval: 0,          // 强制显示所有标签
      textStyle: {
        color: '#666',
        fontSize: 12
      }
    },
    data: xAxisData.value
  },
  yAxis: {
    type: 'value',
    inverse: true,
    position: 'left',
    axisLine: {
      lineStyle: {
        color: '#DCDFE6'
      }
    },
    min: 0
  },
  series: [
    {
      data: yAxisData.value,
      name: '热搜排名',
      center: ['50%', '60%'],
      type: 'line',
      symbol: 'circle',
      symbolSize: 8,
      itemStyle: {
        color: '#409EFF'
      },
      lineStyle: {
        width: 2
      },
    }
  ]
};

const lineChartRef = ref<echarts.ECharts | null>(null);

const initLineChart = () => {
  const chartDom = document.getElementById('chart2');
  if (chartDom) {
    lineChartRef.value = echarts.init(chartDom);
    updateLineChart()
  }
}

const updateLineChart = () => {
  if (!lineChartRef.value) return;

  const newOption = {
    ...lineChartOption,
    xAxis: {
      type: 'category',
      data: xAxisData.value
    },
    series: [{
      data: yAxisData.value,
      type: 'line',
    }]
  };

  lineChartRef.value.setOption(newOption);
};
</script>

<style scoped lang="scss">
.dashboard-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

  :deep(.el-card__body) {
    padding: 0;
  }
}

.chart-container {
  width: 40vw;             // 保持原有宽度设置
  height: 40vh;            // 保持原有高度设置
  margin: 0 auto;          // 水平居中
  position: relative;      // 为子元素绝对定位提供基准
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  display: flex;           // 启用弹性布局
  justify-content: center; // 水平居中
  align-items: center;     // 垂直居中
}

// card标题样式
.card-header {
  padding: 18px 24px;  // 设置内边距
  border-bottom: 1px solid #ebeef5; // 添加底部边框

  // 定义子元素样式
  .card-title {
    font-size: 16px;  // 字体大小
    font-weight: 600; // 字体粗细
    color: #303133; // 字体颜色
  }
}

.demonstration {
  color: var(--el-text-color-secondary);
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 250px;
  margin: 0;
  text-align: center;
}

.comment-container {
  // border: 2px dashed red !important;
  height: 65%;
  padding: 30px;  // 增加容器内边距
  display: flex;
  align-items: center;
  justify-content: center;

  .comment-content {
    // border: 1px solid blue !important;
    width: 100%;
    // 精确计算三行高度：行高1.8 * 字号25px * 3行 = 135px
    max-height: 150px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 5; // 固定显示三行
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.5; // 增加行高
    font-size: 20px; // 放大字号
    color: rgba(0,0,0,0.9);
    border-radius: 6px;
    box-sizing: border-box; // 添加盒模型计算
    word-break: break-all; // 允许长单词换行
    // background: rgba(255,255,255,0.9); // 添加白色背景提高可读性
    // box-shadow: 0 2px 8px rgba(0,0,0,0.1); // 添加轻微阴影
  }
}
</style>